import Portal from '@/utils/Dom/Portal';

import React from 'react';
import Dialog from './Dialog';
import { TMousePosition, TPortalParams, YmDialogProps } from './interface';

//等到DialogWrap 组件加载了再去addEventListenr('click'),那就只能从第二次按钮点击开始监听
let ymDialogMousePosition: TMousePosition;

// ref: https://github.com/ant-design/ant-design/issues/15795
const getClickPosition = (e: MouseEvent) => {
  ymDialogMousePosition = {
    x: e.pageX,
    y: e.pageY,
  };
  // 100ms 内发生过点击事件，则从点击位置动画展示
  // 否则直接 zoom 展示
  // 这样可以兼容非点击方式展开
  // setTimeout(() => {
  //   ymDialogMousePosition = null;
  // }, 100);
};

// 只有点击事件支持从鼠标位置动画展开
document.documentElement.addEventListener('click', getClickPosition, true);

const DialogWrap: React.FC<YmDialogProps> = (props) => {
  const {
    open,
    getContainer,
    forceRender,
    destroyOnClose = false,
    prefixCls = 'ym-dialog',
    mousePosition,
    afterClose,
  } = props;
  const [animatedVisible, setAnimatedVisible] = React.useState<boolean>(open);

  React.useEffect(() => {
    if (open) {
      setAnimatedVisible(true);
    }
  }, [open]);

  if (!forceRender && destroyOnClose && !animatedVisible) {
    return null;
  }

  return (
    <Portal
      forceRender={forceRender}
      visible={open}
      getContainer={getContainer}
    >
      {(portalParams: TPortalParams) => (
        <Dialog
          {...props}
          mousePosition={ymDialogMousePosition ?? mousePosition}
          destroyOnClose={destroyOnClose}
          prefixCls={prefixCls}
          afterClose={() => {
            afterClose?.();
            setAnimatedVisible(false);
          }}
          {...portalParams}
        />
      )}
    </Portal>
  );
};

export default DialogWrap;
